import 'package:blue_classic_plus/BluetoothDevice.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/extension/FFStringExt.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';
import 'package:mybase/base/tool/platformUtils/FFPlatform.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';

import 'blue_classic_plus_platform_interface.dart';

class BlueClassicPlus {
  static const EventChannel _eventChannel =
      EventChannel("blue_classic_plus_eventChannel");
  static BlueClassicPlusBaseDelegate? delegate;

  static initEvent() {
    _eventChannel.receiveBroadcastStream().listen((map) {
      /**
          map结构：
          {
          "type":"事件类型",
          "code":事件状态码,
          "msg": "message"
          }
       */
      String? type = globalSafeValueFromMap<String>(map, "type");
      int? code = globalSafeValueFromMap<int>(map, "code");

      ///不是有效的消息
      if (FFEmpty.stringIsEmpty(type) || code == null) {
        return;
      }

      print("BlueClassicPlus 监听到的消息 = $map");
      switch (type) {
        case "serverMsg":

          ///客户端收到服务端发送的消息
          String? msg = globalSafeValueFromMap(map, "msg");
          if (FFEmpty.stringIsEmpty(msg)) return;
          delegate?.blueClientResvMsg(msg!);
          break;

        case "serverState":

          ///服务端状态的变化
          switch (code) {
            case 0:
              delegate?.blueStateUnknown();
              break;
            case 1:
              delegate?.blueStateResetting();
              break;
            case 2:
              delegate?.blueStateUnSupported();
              break;
            case 3:
              delegate?.blueStateUnauthorized();
              break;
            case 4:
              delegate?.blueStateOff();
              break;
            case 6:
              delegate?.blueServerStartFail();
              break;
            case 7:
              delegate?.blueServerStartSuccess();
              break;
            case 8:
              delegate?.blueClientConnected();
              break;
            case 10:
              delegate?.blueClientDisConnected();
              break;
          }

          break;

        case "clientState":
          /**
            map结构：
            {
            "type":"事件类型",
            "code":事件状态码,
            "msg": "message"
            }
         */

          ///客户端状态的变化
          switch (code) {
            case 0:
              delegate?.blueStateUnknown();
              break;
            case 1:
              delegate?.blueStateResetting();
              break;
            case 2:
              delegate?.blueStateUnSupported();
              break;
            case 3:
              delegate?.blueStateUnauthorized();
              break;
            case 4:
              delegate?.blueStateOff();
              break;
            case 8:
              delegate?.blueClientConnected();
              break;
            case 9:
              delegate?.blueClientFailToConnect();
              break;
            case 10:
              delegate?.blueClientDisConnected();
              break;
          }

          break;
        default:
        //print("未处理的监听 BlueClassicPlus listen msg = $map");
      }
    });
  }

  static BluetoothDevice getDeviceByMap(Object? map) {
    return BluetoothDevice(
      name: globalSafeValueFromMap(map, "name"),
      address: globalSafeValueFromMap(map, "address"),
    );
  }

  Future<String?> getPlatformVersion() {
    return BlueClassicPlusPlatform.instance.getPlatformVersion();
  }

  ///请求蓝牙权限
  Future<bool> bluetoothPermission() async {
    return BlueClassicPlusPlatform.instance.bluetoothPermission();
  }

  ///蓝牙是否可用
  Future<bool> bluetoothIsSupport() {
    return BlueClassicPlusPlatform.instance.bluetoothIsSupport();
  }

  ///蓝牙是否打开
  Future<bool> bluetoothIsEnabled() {
    return BlueClassicPlusPlatform.instance.bluetoothIsEnabled();
  }

  ///蓝牙是否可见
  Future<bool> bluetoothEnableEetectability() {
    return BlueClassicPlusPlatform.instance.bluetoothEnableEetectability();
  }

  ///查找系统里面配对好的设备
  Future<List<BluetoothDevice>> bluetoothBondedDevices() async {
    List<Object?> devices =
        await BlueClassicPlusPlatform.instance.bluetoothBondedDevices();
    List<BluetoothDevice> results = [];
    for (var map in devices) {
      results.add(BlueClassicPlus.getDeviceByMap(map));
    }

    return results;
  }

  ///扫描设备
  Future<bool> bluetoothStartDiscovery(
      {required String uuid, required String name}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothStartDiscovery(uuid: uuid, name: name);
  }

  ///结束扫描
  Future<void> bluetoothEndDiscovery() {
    return BlueClassicPlusPlatform.instance.bluetoothEndDiscovery();
  }

  ///作为服务端开启
  Future<bool> bluetoothStartServer(
      {required String uuid, required String name}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothStartServer(uuid: uuid, name: name);
  }

  ///服务端关闭
  Future<bool> bluetoothStopServer({String? uuid, String? name}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothStopServer(uuid: uuid, name: name);
  }

  ///作为客户端连接
  Future<bool> bluetoothStartClient(
      {required String uuid, required BluetoothDevice device}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothStartClient(uuid: uuid, device: device);
  }

  ///客户端断开连接
  Future<bool> bluetoothStopClient(
      {required String uuid, required String device}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothStopClient(uuid: uuid, device: device);
  }

  ///服务端广播消息
  Future<bool> bluetoothServerBroadcastMsg({required String msg}) {
    return BlueClassicPlusPlatform.instance
        .bluetoothServerBroadcastMsg(msg: msg);
  }

  ///客户端发送消息
  Future<bool> bluetoothClientSendMsg({required String msg}) {
    return BlueClassicPlusPlatform.instance.bluetoothClientSendMsg(msg: msg);
  }
}

///蓝牙状态变化
//  0, 未知
//  1 重置状态
//  2 不支持使用蓝牙
//  3 未授权状态
//  4 蓝牙关闭状态
//  5 蓝牙打开状态

//  8 连接成功
//  10 连接失败

///服务端独有
//  6 蓝牙服务端开启出错
//  7 蓝牙服务端开启监听中
//  - 蓝牙服务端主动关闭 不提示

///客服端独有
//  9 客户端发起的连接失败

abstract class BlueClassicPlusBaseDelegate {
  ///服务端 开启成功
  void blueServerStartSuccess();

  ///服务端 开启失败
  void blueServerStartFail();

  ///服务端收到 客户端连接成功了
  void blueServerRecvClientConnected(BluetoothDevice device);

  ///服务端收到 客户端断开了连接
  void blueServerRecvClientDisconnected(BluetoothDevice device);

  ///客户端 连接蓝牙服务端成功了
  void blueClientConnected();

  ///客户端 连接蓝牙服务端失败
  void blueClientFailToConnect();

  ///客户端 与蓝牙服务端断开连接了
  void blueClientDisConnected();

  ///客户端接收到的消息
  void blueClientResvMsg(String msg);

  ///蓝牙状态:未打开
  void blueStateOff();

  ///蓝牙状态:未授权
  void blueStateUnauthorized();

  ///蓝牙状态:不支持
  void blueStateUnSupported();

  ///蓝牙状态:未知错误
  void blueStateUnknown();

  ///蓝牙状态:重置状态
  void blueStateResetting();
}

class BlueClassicPlusDelegate implements BlueClassicPlusBaseDelegate {
  @override
  void blueClientConnected() {
    FFLog.success("flutter 蓝牙客户端 连接蓝牙服务端成功了");
  }

  @override
  void blueClientFailToConnect() {
    FFLog.success("flutter 蓝牙客户端 连接蓝牙服务端失败了");
  }

  @override
  void blueClientDisConnected() {
    FFLog.success("flutter 蓝牙客户端 与蓝牙服务端断开连接了");
  }

  @override
  void blueClientResvMsg(String msg) {
    FFLog.success("flutter 蓝牙客户端 收到消息: $msg");
  }

  @override
  void blueServerRecvClientConnected(BluetoothDevice device) {
    FFLog.success("flutter 蓝牙服务端 收到客户端连接");
  }

  @override
  void blueServerRecvClientDisconnected(BluetoothDevice device) {
    FFLog.success("flutter 蓝牙服务端 收到客户端断开");
  }

  @override
  void blueServerStartFail() {
    FFLog.success("flutter 蓝牙服务端 开启失败");
  }

  @override
  void blueServerStartSuccess() {
    FFLog.success("flutter 蓝牙服务端 开启成功");
  }

  @override
  void blueStateOff() {
    FFLog.success("flutter 蓝牙状态 已关闭");
  }

  @override
  void blueStateResetting() {
    FFLog.success("flutter 蓝牙状态 重置中");
  }

  @override
  void blueStateUnSupported() {
    FFLog.success("flutter 蓝牙状态 不支持");
  }

  @override
  void blueStateUnauthorized() {
    FFLog.success("flutter 蓝牙状态 未授权");
  }

  @override
  void blueStateUnknown() {
    FFLog.success("flutter 蓝牙状态 未知错误");
  }
}
